#ifndef IMAGEJPEG_H
#define IMAGEJPEG_H

#include "IncFreeTrack.h"
#include <stdio.h>
#include "image.h"

// We use the libjpeg to manipualte JPEG files...
// libjpeg is C code, so we need to "mask" it properly
extern "C" {
    #include "libjpeg/jpeglib.h"
}

class ImageJpeg : public Image
{
public:
    // Used to load a jpeg
    ImageJpeg( const QString& );
    // We need to free the libjpeg data structures
    ~ImageJpeg();
    // Check if this is a valid jpeg (use only on existing files)
    bool isValid();

    // Read cycle: call this first...
    bool startReading( int zoom, int& output_width, int& output_height );
    // ...then this until all image has been read!
    uchar* readScanline();

    // Write cycle: call this first...
    bool startWriting( int width, int height );
    // ...then this until all image has been written!
    bool writeScanline( uchar* );

    // Quick function to read an image into a QImage
    bool readImage( QImage* image,
                    const QRect& source_rect = QRect(),
                    const QRect& dest_rect = QRect(),
                    int zoom = 1 );

private:
    // Internal libjpeg data structures
    struct jpeg_error_mgr jerr;

    // I prefer to use simply an old-style FILE* for libjpeg...
    FILE* pFile;

private: // read data section
    // The jpeglib read structture
    struct jpeg_decompress_struct read_cinfo;
    // The scanline buffers
    JSAMPLE** scanlines;
    // The number of buffered scanlines
    int n_buffered_scanlines;
    // The last returned buffered scanline
    int last_buffered_scanline;
    // Support zooms factors of 16,32 and 64 by manually interpolating lines and pixels
    // This will only be the "extra" above 8. So, for example, 2 = 8*2 = zoom factor 16.
    int extra_zoom;

private: // write data saection
    struct jpeg_compress_struct write_cinfo;

};
#endif // IMAGEJPEG_H
